package com.graduation.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.graduation.springbootinit.common.BaseResponse;
import com.graduation.springbootinit.common.ResultUtils;
import com.graduation.springbootinit.model.entity.ActivityPart.QuizChallenge;
import com.graduation.springbootinit.model.entity.ActivityPart.QuizQuestion;
import com.graduation.springbootinit.model.entity.ActivityPart.QuizRecord;
import com.graduation.springbootinit.model.entity.User;
import com.graduation.springbootinit.model.request.QuizSubmitRequest;
import com.graduation.springbootinit.model.request.QuizQuestionBatchRequest;
import com.graduation.springbootinit.service.QuizChallengeService;
import com.graduation.springbootinit.service.UserService;
import com.graduation.springbootinit.common.ErrorCode;
import com.graduation.springbootinit.exception.BusinessException;
import com.graduation.springbootinit.mapper.QuizRecordMapper;
import com.graduation.springbootinit.model.vo.QuizQuestionVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/quiz")
public class ActivityQuestionController {

    @Resource
    private QuizChallengeService quizChallengeService;

    @Resource
    private UserService userService;

    @Resource
    private QuizRecordMapper quizRecordMapper;

    // 管理员创建答题挑战
    @PostMapping("/challenge/add")
    public BaseResponse<Boolean> createChallenge(@RequestBody QuizChallenge challenge, HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        // TODO: 验证用户是否是管理员
        quizChallengeService.createChallenge(challenge);
        return ResultUtils.success(true);
    }

    // 管理员添加题目
    @PostMapping("/question/add")
    public BaseResponse<Boolean> addQuestion(@RequestBody QuizQuestion question, HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        // TODO: 验证用户是否是管理员
        quizChallengeService.addQuestion(question);
        return ResultUtils.success(true);
    }

    // 管理员批量添加题目
    @PostMapping("/question/batch/add")
    public BaseResponse<Boolean> addQuestionBatch(@RequestBody QuizQuestionBatchRequest request, 
            HttpServletRequest httpRequest) {
        User user = userService.getLoginUser(httpRequest);
        // TODO: 验证用户是否是管理员
        
        // 设置challengeId
        request.getQuestions().forEach(question -> 
            question.setChallengeId(request.getChallengeId()));
        
        quizChallengeService.addQuestionBatch(request.getChallengeId(), request.getQuestions());
        return ResultUtils.success(true);
    }

    // 获取进行中的挑战列表
    @GetMapping("/challenge/list")
    public BaseResponse<Page<QuizChallenge>> listChallenges(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        return ResultUtils.success(quizChallengeService.getOngoingChallenges(pageNum, pageSize));
    }

    // 获取挑战的题目列表
    @GetMapping("/challenge/{challengeId}/questions")
    public BaseResponse<List<QuizQuestionVO>> getChallengeQuestions(@PathVariable Long challengeId) {

        return ResultUtils.success(quizChallengeService.getChallengeQuestions(challengeId));
    }

    // 提交答案
    @PostMapping("/submit")
    public BaseResponse<QuizRecord> submitAnswers(@RequestBody QuizSubmitRequest request, HttpServletRequest httpRequest) {
        User user = userService.getLoginUser(httpRequest);
        QuizRecord record = quizChallengeService.submitAnswers(user.getId(), 
                request.getChallengeId(), request.getAnswers());
        return ResultUtils.success(record);
    }

    // 管理员结束挑战并发放奖励
    @PostMapping("/challenge/{challengeId}/end")
    public BaseResponse<Boolean> endChallenge(@PathVariable Long challengeId, HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        // TODO: 验证用户是否是管理员
        quizChallengeService.endChallengeAndReward(challengeId);
        return ResultUtils.success(true);
    }

    // 获取用户答题历史
    @GetMapping("/history")
    public BaseResponse<List<QuizRecord>> getQuizHistory(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        List<QuizRecord> history = quizChallengeService.getUserQuizHistory(user.getId());
        return ResultUtils.success(history);
    }

    // 获取挑战详情（包括参与人数、平均分等统计信息）
    @GetMapping("/challenge/{challengeId}/stats")
    public BaseResponse<Map<String, Object>> getChallengeStats(@PathVariable Long challengeId) {
        return ResultUtils.success(quizChallengeService.getChallengeStats(challengeId));
    }

} 